package jmine.tec.utils.reflection.fast.asm;

/**
 * @author takeshi
 */
public abstract class AbstractClassGenerator {

    public static final String JMINE_TEC_GENERATED = "jmine/tec/generated/";

    private final OpenClassLoader loader;

    /**
     * @param loader {@link OpenClassLoader}
     */
    public AbstractClassGenerator(OpenClassLoader loader) {
        super();
        this.loader = loader;
    }

    /**
     * Load
     * 
     * @param <E> type
     * @param clName classname with "/"
     * @param byteArray the class
     * @param boundType Type
     * @return <E>
     */
    public final <E> E loadClass(String clName, byte[] byteArray, Class<E> boundType) {
        Class<?> type = this.loader.defineClass(clName.replaceAll("/", "."), byteArray);
        try {
            return boundType.cast(type.newInstance());
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * @param type the type
     * @return {@link String}
     */
    public static String getClassName(Class<?> type) {
        int post = type.getName().lastIndexOf('.');
        if (post > -1) {
            return type.getName().substring(post + 1);
        }
        return type.getName();
    }

}
